var id = getUrlString('type');
var markid = getUrlString('markid');//'3b70887e5d841ff8ab7388ea5f41a5af'
var openid = getUrlString('openid');
var ipAddress;
var search;
$(function () {
    //投票贴详情
    function voteDetail() {
        getData('post','/niu/apiv3/vote_article.php',{'id':id},function (data) {
            console.log(data);
            if(data.resultcode === '0' ){
                //判断投票登录方式
                if(data.data.logintype === '0'){
                    $('.phoneVerify').hide()
                }else {
                    $('.phoneVerify').fadeIn();
                }
                var endTime = data.data.endtime;
                $('#totalcount').html(data.data.totalcount);
                $('#optioncount').html(data.data.optioncount);
                $('.poster').css({
                    'background-image': 'url('+data.data.picurl+')',
                    'background-size': 'cover',
                    'background-repeat-x': 'no-repeat',
                    'background-repeat-y': 'no-repeat'
                });
                var intro = data.data.intro;
                $('#intro').html(escape2Html(intro));

                var dateEnd = new Date();//获取当前时间
                var datetime=dateEnd.getFullYear()  + (zeroFill(dateEnd.getMonth() + 1)) + zeroFill(dateEnd.getDate()) +
                    zeroFill(dateEnd.getHours())  + zeroFill(dateEnd.getMinutes())  + zeroFill(dateEnd.getSeconds());
                $('#countDown').html('投票结束倒计时：'+getYMDHMS(datetime,endTime));

                //投票分享
                var titleShare = data.data.title;
                var picUrl = data.data.picurl;
                var introShare = data.data.sharetext;
                var url = '';
            }else {
                laymsg(data.msg)
            }
        })
    }
    voteDetail();

    //获取验证码
    function getCode(phone) {
        if(phoneNumberVer(phone)){
            getData('post','/niu/api/member_login_sms_wx.php',{'phone':phone},function (data) {
                console.log(data);
                if(data.resultcode == 0){
                    laymsg(data.msg);
                    //倒计时
                    var second = 60;
                    var timer = null;
                    timer = setInterval(function(){
                        second -= 1;
                        if(second > 0 ){
                            $('.codeBtnActive').hide();
                            $('.codeBtn').html(second+'秒').show();
                        }else{
                            clearInterval(timer);
                            $('.codeBtn').hide();
                            $('.codeBtnActive').show();
                        }
                    },1000);
                }else {
                    laymsg(data.msg)
                }
            })
        }
    }

    $('.codeBtnActive').click(function () {
        var phone = $('#phoneNum').val();
        getCode(phone);
    });

    $('.phoneVerifyCancel').click(function () {
        $('.phoneVerify').fadeOut();
    });

    //手机绑定微信
    (function () {
        $('.pickUpBtn').click(function () {
            var phone = $('#phoneNum').val();
            var code = $('#phoneCode').val();
            if(phone == ''){
                laymsg('手机号不能为空!');
                return
            }

            if(code == ''){
                laymsg('验证码不能为空!');
                return
            }
            getData('post','/niu/api/member_login_phone_wx.php',{'phone':phone,'openid1':openid,'pw':code},function (data) {
                console.log(data);
                if(data.resultcode == 0){
                    markid = data.markid;
                    setItem('phone',data.phone);
                    setItem('markid',markid);
                    $('.phoneVerify').fadeOut();
                }else {
                    laymsg(data.msg)
                }
            })
        })
    })();

    //投票贴列表
    function voteList(sort) {
        layLoading();
        var data = {
            'id':id,
            'sort':sort,
            'search':search
        };
        getData('post','/niu/apiv3/vote_options.php',data,function (data) {
            console.log(data);
            layer.closeAll('loading');
            if(data.resultcode === '0' ){
                if(data.pagesize === '0'){
                    $('#voteList').empty().hide();
                    $('.noData').show();
                }else {
                    $('.noData').hide();
                    var append = '';
                    $(data.data).each(function () {
                        append += '<li>' +
                            '                <div class="pic">' +
                            '                    <img src="'+ this.picurl +'" alt="">' +
                            '                    <div class="dayNum">'+this.id+'</div>' +
                            '                </div>' +
                            '                <div class="name">'+this.title+'</div>' +
                            '                <div class="voteNum"><span>'+this.totalcount+'</span>票</div>' +
                            '                <div class="voteBtn">投票</div>' +
                            '                <input type="hidden" value="'+ this.id +'"> '+
                            '            </li>'
                    });
                    $('#voteList').empty().append(append).show();
                    $('#voteList .voteBtn').click(function () {
                        var opid = $(this).next('input').val();
                        var voteNum = $(this).prev('.voteNum').find('span').html();
                        var _this = $(this);
                        if(ipAddress == undefined || ipAddress == ''){
                            ipAddress = '0.0.0.0'
                        }
                        var data = {
                            'markid':markid,
                            'aid':id,
                            'opid':opid  ,
                            'ip': ipAddress,
                            'fromtag':'wx',
                        };
                        getData('post','/niu/apiv3/vote_dovote.php',data,function (data) {
                            console.log(data);
                            if(data.resultcode === '0' ){
                                layer.confirm('投票成功,去关注公众号!', {
                                    btn: ['确定', '取消'] //按钮
                                }, function() {
                                    window.location.href = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1NTQ3ODc1Mg==&scene=110#wechat_redirect'
                                }, function() {

                                });
                                voteNum ++;
                                _this.prev('.voteNum').find('span').html(voteNum);
                                // _this.html('已投票')
                            }else {
                                laymsg(data.msg)
                            }
                        })
                    })
                }

            }else {
                laymsg(data.msg)
            }
        })
    }

    //默认调用最新投票列表
    voteList(2);





    //判断是否投过票
    function isVote() {
        getData('post','/niu/apiv3/vote_isvote.php',{'markid':markid,'aid':id},function (data) {
            console.log(data);
            if(data.resultcode === '0' ){

            }else {
                laymsg(data.msg)
            }
        })
    }
    // isVote();

    //切换人气投票贴列表
    $('.caseBoxBtn').click(function () {
        $('.tabSwitch li span').removeClass('active');
        $(this).find('span').addClass('active');
        voteList(1);
    });

    //切换最新投票贴列表
    $('.communityBtn').click(function () {
        $('.tabSwitch li span').removeClass('active');
        $(this).find('span').addClass('active');
        voteList(2);
    });

    //搜索
    $('.searchBtn').click(function () {
        search = $('#searchInput').val();
        voteList(2);
    });

    function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
        //compatibility for firefox and chrome
        var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        var pc = new myPeerConnection({
                iceServers: []
            }),
            noop = function() {},
            localIPs = {},
            ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
            key;

        function iterateIP(ip) {
            if (!localIPs[ip]) onNewIP(ip);
            localIPs[ip] = true;
        }

        //create a bogus data channel
        pc.createDataChannel("");

        // create offer and set local description
        pc.createOffer().then(function(sdp) {
            sdp.sdp.split('\n').forEach(function(line) {
                if (line.indexOf('candidate') < 0) return;
                line.match(ipRegex).forEach(iterateIP);
            });

            pc.setLocalDescription(sdp, noop, noop);
        }).catch(function(reason) {
            // An error occurred, so handle the failure to connect
        });

        //sten for candidate events
        pc.onicecandidate = function(ice) {
            if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
            ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        };
    }
    //获取本机Ip
    getUserIP(function(ip){
        ipAddress = ip
    });
});